import { UploadOutlined } from '@ant-design/icons';
import '@ant-design/compatible/assets/index.css';
import { FormInstance } from 'antd/lib/form';
import { Avatar, Button, Card, Col, Input, message, Row, Upload, Radio, Form } from 'antd';
import React, { Component } from 'react';
import { connect } from 'dva';
import { windowUrl } from '../../../../../public/global';
import { getToken } from '@/utils/utils';
import { getOptAuthHeaders } from '@/utils/common';
import CropperAvatar from './CropperAvatar';

const FormItem = Form.Item;
const mapStateToProps = (state: any) => ({
  user: state.user,
  userInfo: state.menu.userProfile,
  loading: state.loading.models['user/updateCurrent'],
});

class BaseView extends Component<any, any> {
  formRef = React.createRef<FormInstance>();

  constructor(props: any) {
    super(props);
    this.state = {
      fileList: [], // 文件列表
      fileUrl: undefined, // 文件url
      open: false,
      avatarFile: undefined
    };
  }

  async componentDidMount() {
    const { dispatch } = this.props;
    await dispatch({
      type: 'user/fetchCurrent',
    });
    const currentUser = this.props.user.currentUser;
    const fields = [
      { name: 'nickName', value: currentUser ? currentUser.nickName : '' },
      { name: 'userMobile', value: currentUser ? currentUser.userMobile : '' },
      { name: 'userSex', value: currentUser ? currentUser.userSex : '' },
      { name: 'userPhone', value: currentUser ? currentUser.userPhone : '' },
      { name: 'userHeadImg', value: currentUser ? currentUser.userHeadImg : '' },
      { name: 'userMail', value: currentUser ? currentUser.userMail : '' },
    ];

    this.setState({
      fileUrl: currentUser ? currentUser.userHeadImg : '',
    });
    this.formRef.current?.setFields(fields);
  }

  handleFileChange = (info: any) => {
    let { fileList, file } = info;
    fileList = fileList.slice(-1);
    if (
      file.status === 'done' &&
      file.response &&
      file.response.statusCode === '0' &&
      file.response.data
    ) {
      message.success(`${file.name} 上传成功`);
      this.setState({ fileUrl: file.response.data.fileUrl });
    } else if (file.status === 'done' && file.response && file.response.statusCode !== '0') {
      message.error(file.response.statusMessage);
      this.setState({ fileList: [] });
      return;
    } else if (file.status === 'error') {
      message.error(`${file.name} 上传失败`);
      this.setState({ fileList: [] });
      return;
    } else if (!file.status) {
      this.setState({ fileList: [] });
      return;
    }
    this.setState({ fileList });
  };

  beforeFileUpload = (file: any) => {
    if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
      message.error('请上传JPG或PNG格式图片！');
      return false;
    }
    if (file.size / 1024 / 1024 > 5) {
      message.error(`图片大小不能大于5MB！`);
      return false;
    }
    return true;
  };

  handlerSubmit = () => {
    this.formRef.current?.submit();
  };

  normFile = (e: any) => {
    let { fileList, file } = e;
    fileList = fileList.slice(-1);
    if (
      file.status === 'done' &&
      file.response &&
      file.response.statusCode === '0' &&
      file.response.data
    ) {
      message.success(`${file.name} 上传成功`);
      this.setState({
        fileUrl: file.response.data.fileUrl,
      });
      return file.response.data.fileUrl;
    } else if (file.status === 'done' && file.response && file.response.statusCode !== '0') {
      message.error(file.response.statusMessage);
      return;
    } else if (file.status === 'error') {
      message.error(`${file.name} 上传失败`);
      return;
    } else if (!file.status) {
      return;
    }
  };

  onFinish = (values: any) => {
    const {
      user: { currentUser },
      dispatch,
    } = this.props;
    const { fileUrl } = this.state;
    const pushData = { ...values };
    pushData.userHeadImg = fileUrl
      ? fileUrl
      : currentUser && currentUser.userHeadImg
      ? currentUser.userHeadImg
      : 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png';
    dispatch({
      type: 'user/updateCurrent',
      payload: { ...pushData },
      callback: (response: any) => {
        message.success('更新成功');
        // 重新查询用户信息
        dispatch({
          type: 'user/fetchCurrent',
        });
      },
    });
  };

  customRequest = async (options) => {
    this.setState({
      open: true,
      avatarFile: options
    })
  }

  onCloseCropperModal = () => {
    this.setState({
      open: false,
      avatarFile: undefined
    })
  }

  render() {
    const {
      user: { currentUser },
    } = this.props;
    const { fileUrl, open, avatarFile } = this.state;
    const uploadUrl = '/common/upload/img?checkWidth=200&checkHeight=200';
    const str = `${windowUrl}${uploadUrl}`;
    const imgUrl = fileUrl
      ? fileUrl
      : currentUser && currentUser.userHeadImg
      ? currentUser.userHeadImg
      : 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png';
    return (
      <Card bordered={false}>
        <Form onFinish={this.onFinish} ref={this.formRef}>
          <Row gutter={24}>
            <Col span={12}>
              <FormItem
                name="nickName"
                label="昵称"
                rules={[{ required: false, message: '请输入昵称', max: 20 }]}
              >
                <Input maxLength={20} placeholder={'请输入昵称'} />
              </FormItem>
              <FormItem
                name="userMobile"
                label="手机"
                rules={[{ required: false, message: '请输入手机号', max: 15 }]}
              >
                <Input placeholder={'请输入手机号'} maxLength={15} />
              </FormItem>
              <FormItem name="userSex" label="性别">
                <Radio.Group>
                  <Radio value={0}>男</Radio>
                  <Radio value={1}>女</Radio>
                </Radio.Group>
              </FormItem>
              <FormItem
                name="userPhone"
                label="座机"
                rules={[
                  {
                    required: false,
                    message: '请输入正确格式的座机',
                    pattern: /^[0][1-9]{2,3}-[0-9]{5,10}$/,
                  },
                ]}
              >
                <Input placeholder={'请输入座机'} />
              </FormItem>
              <FormItem
                name="userMail"
                label="邮箱"
                rules={[
                  {
                    required: false,
                    message: '请输入正确格式的邮箱',
                    max: 64,
                    pattern: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/,
                  },
                ]}
              >
                <Input maxLength={64} placeholder={'请输入邮箱'} />
              </FormItem>
              <Button type="primary" style={{ width: '100%' }} onClick={this.handlerSubmit}>
                更 新 设 置
              </Button>
            </Col>
            <Col span={8} offset={2}>
              <FormItem
                name="userHeadImg"
                getValueFromEvent={this.normFile}
                rules={[{ required: false }]}
              >
                <span>头像</span>
                <div>
                  <Avatar size={150} src={imgUrl} alt="avatar" />
                </div>
                <Upload
                  headers={{
                    OptAuthorization: `${getToken()}`,
                    ...getOptAuthHeaders(),
                  }}
                  action={str}
                  listType="text"
                  multiple={false}
                  // fileList={fileList}
                  onChange={this.handleFileChange}
                  // beforeUpload={this.beforeFileUpload}
                  showUploadList={false}
                  customRequest={this.customRequest}
                >
                  <div style={{ marginTop: 24, width: '100%', marginLeft: 30 }}>
                    <Button icon={<UploadOutlined />} type="primary" size="small">
                      上传头像
                    </Button>
                  </div>
                </Upload>
              </FormItem>
            </Col>
          </Row>
        </Form>
        {open && (
          <CropperAvatar 
            open={open}
            avatarFile={avatarFile}
            onClose = { this.onCloseCropperModal }
          />
        )}
      </Card>
    );
  }
}

export default connect(mapStateToProps)(BaseView);
